package com.scy.java.Array;
//二分法查找指定元素
public class BinarySearch {
    public static void main(String[] args) {
        //二分法查找要求，数组必须是有序的
        int[] arr = {-99,-55,-3,0,2,33,45,256,999};
        //定义首尾的索引
        int head = 0 ;
        int end = arr.length-1;
        //定义临时变量(开关)
        boolean isFlag =false;
        //指定目标元素
        int value = 4;

        while (head<=end){
            //获取中间下标值
            int middle = (head+end)/2;
            if (arr[middle]==value){
                System.out.println("找到指定的元素下标为："+middle);
                //找到了开关就关上
                isFlag = true;
                break;
            } else if (arr[middle]>value) {
                end=middle-1;
            }else if(arr[middle]<value) {
                head=middle+1;
            }
        }
        if (!isFlag){
            System.out.println("未找到指定元素");
        }
    }
}
